package cl.orangepeople.whyem.portal.signup.action;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.struts.BaseStrutsPortletAction;
import com.liferay.portal.kernel.struts.StrutsPortletAction;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.util.PortalUtil;

public class CustomUserRegistrationPortletAction extends BaseStrutsPortletAction {
    private static final Logger logger;

    static {
	logger = LoggerFactory.getLogger(CustomUserRegistrationPortletAction.class);
    }
	
    public void processAction(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
	ServletRequest r = PortalUtil.getHttpServletRequest(actionRequest);
	while(r instanceof ServletRequestWrapper){
	    r = ((ServletRequestWrapper) r).getRequest();
	}
	HttpSession session = ((HttpServletRequest) r).getSession();
	String sessionClientID = (String) session.getAttribute("clientID");
	String signupClientID = actionRequest.getParameter("screenName");
	
	boolean clientIDMatches = StringUtils.equals(sessionClientID, signupClientID);

	if (clientIDMatches) {
	    logger.info("Music player sucessfully matched, redirecting to original user registration action...");
	    originalStrutsPortletAction.processAction(originalStrutsPortletAction, portletConfig, actionRequest, actionResponse);
	} else {
	    SessionErrors.add(actionRequest, "invalid.client.id");
	    logger.error("Client ID match failed, rendering error message...");
	}
    }
    
    @Override
    public String render(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig, RenderRequest renderRequest, RenderResponse renderResponse) throws Exception {
	String ret = originalStrutsPortletAction.render(null, portletConfig, renderRequest, renderResponse);
	renderRequest.setAttribute(WebKeys.PORTLET_DECORATE, Boolean.TRUE);
	return ret;
    }
}